//
//  EverydayView.m
//  TengyunStation
//
//  Created by Johnny on 15/8/31.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "EverydayView.h"
#import "SocketRequest.h"
#import "EveryGroup.h"
#import "EveryExpressCell.h"
#import "Singleton.h"
#import "TSHeader.h"

@interface EverydayView ()<SocketRequestDelegate> {
    SocketRequest *_socketRequest;
    int _positionPage;
}

@end

@implementation EverydayView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = SpaceColor;
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
        self.everyGroupList = [NSMutableArray arrayWithCapacity:1];
        _positionPage = 1;
        self.dataSource = self;
        self.delegate = self;
        self.pullTableViewDelegate = self;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self makeLoading];
    }
    return self;
}

- (void)setExpressType:(NSString *)expressType {
    _expressType = expressType;
    [self getEveryExpressFromSqlite];
}

- (void)reloadExpressListData {
    _positionPage = 1;
    [self getEveryExpressSocket];
}

- (void)getEveryExpressFromSqlite {
    NSString *sql = [NSString stringWithFormat:@"WHERE socketType = '%@' ORDER BY receiveTime DESC",self.expressType];
    NSArray *array = [EveryExpress findByCriteria:sql];
    for (EveryExpress *express in array) {
        EveryGroup *group = [self.everyGroupList lastObject];
        if ([express.showDay isEqualToString:group.showDay]) {
            [group.expressList addObject:express];
        } else {
            EveryGroup *anotherGroup = [[EveryGroup alloc] initWithEveryExpress:express];
            [anotherGroup.expressList addObject:express];
            [self.everyGroupList addObject:anotherGroup];
        }
    }
    [self reloadTableViewWithLoaded:YES];
    [self performSelector:@selector(delayLoading) withObject:nil afterDelay:0.1];
}

- (void)delayLoading {
    if (self.everyGroupList.count > 0) {
        [ToastActivity makeActivity:@"正在加载数据..." InView:self.superview];
    }
    [self getEveryExpressSocket];
}

- (void)getEveryExpressSocket {
    if (self.everyGroupList.count <= 0) {
        [self makeLoading];
    } else {
        [self  makeNone];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STR4"]];
    [mutableData appendBytes:[SocketMethod checkLegal:self.expressType] length:2];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    NSString *positionString = [NSString stringWithFormat:@"%d",_positionPage];
    [mutableData appendBytes:[SocketMethod checkLegal:positionString] length:16];
    [mutableData appendBytes:[SocketMethod checkLegal:@"10"] length:16];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

- (void)reloadTableViewWithLoaded:(BOOL)isLoaded {
    self.isShowFooterView = !isLoaded;
    if (self.everyGroupList.count <= 0) {
        if ([self.expressType isEqualToString:@"00"]) {
            [self makeTip:@"无快件"];
        } else if ([self.expressType isEqualToString:@"01"]) {
            [self makeTip:@"无未签收快件"];
        } else if ([self.expressType isEqualToString:@"02"]) {
            [self makeTip:@"无已签收快件"];
        }
    } else {
        self.backgroundView = nil;
    }
    [self reloadData];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    [self endRefreshPullTableView];
    [ToastActivity dismissInView:self.superview];
    if ([code isEqualToString:SuccessSocket]) {
        if (_positionPage == 1) {
            [self.everyGroupList removeAllObjects];
            NSString *sql = [NSString stringWithFormat:@"WHERE socketType = '%@'",self.expressType];
            [EveryExpress deleteObjectsByCriteria:sql];
        }
        NSString *content = [SocketMethod stringDecryHexData:data];
        DLog(@"%@",content);
        NSArray *array = [content componentsSeparatedByString:@"|"];
        int i = 0;
        for (NSString *string in array) {
            if (string.length > 0) {
                EveryGroup *group = [self.everyGroupList lastObject];
                EveryExpress *express = [[EveryExpress alloc] initWithString:string];
                express.socketType = self.expressType;
                [express saveOrUpdate];
                if ([express.showDay isEqualToString:group.showDay]) {
                    [group.expressList addObject:express];
                } else {
                    EveryGroup *anotherGroup = [[EveryGroup alloc] initWithEveryExpress:express];
                    [anotherGroup.expressList addObject:express];
                    [self.everyGroupList addObject:anotherGroup];
                }
                i ++;
            }
        }
        [self reloadTableViewWithLoaded:((i < 10) ? YES : NO)];
    } else {
        if (self.everyGroupList.count <= 0) {
            [self makeTip:msg];
        } else {
            [DSToast showText:msg InView:self.superview];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    [self endRefreshPullTableView];
    [ToastActivity dismissInView:self.superview];
    if (self.everyGroupList.count <= 0) {
        [self makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getEveryExpressSocket)];
    }
    [DSToast showText:msg InView:self.superview];
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.everyGroupList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    EveryGroup *group = [self.everyGroupList objectAtIndex:section];
    return group.expressList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    EveryGroup *group = [self.everyGroupList objectAtIndex:section];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 1, 150, 20)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:11];
    label.textColor = TipTextColor;
    label.text = [NSString stringWithFormat:@"%@(%d)",group.showDay,group.dayCount];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"EveryExpressCell";
    EveryExpressCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"EveryExpressCell" owner:self options:nil] lastObject];
    }
    EveryGroup *group = [self.everyGroupList objectAtIndex:indexPath.section];
    EveryExpress *express = [group.expressList objectAtIndex:indexPath.row];
    [cell reloadEveryExpressCellWithEveryExpress:express];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([_everydayViewDelegate respondsToSelector:@selector(everydayView:IndexPath:)]) {
        [_everydayViewDelegate everydayView:self IndexPath:indexPath];
    }
}
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self pullScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self pullscrollViewDidEndDragging:scrollView];
}

#pragma mark PullTableViewDelegate
- (void)startRefreshHeaderView {
    _positionPage = 1;
    [self getEveryExpressSocket];
}

- (void)startRefreshFooterView {
    _positionPage += 10;
    [self getEveryExpressSocket];
}

- (void)dealloc {
    _socketRequest = nil;
    self.everyGroupList = nil;
}

@end
